package com.baitiaojun.gateway.support;

import com.baitiaojun.api.vo.JsonRes;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.ByteBuffer;

/**
 * @类名 support
 * @描述
 * @作者 白条君
 * @创建日期 2022/10/28 21:04
 * @版本 1.0
 */
public class FilterSupport {

    public static <T> Mono<Void> response(ServerWebExchange exchange, T data) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("content-type", "application/json;charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        ByteBuffer buffer = null;
        try {
            buffer = ByteBuffer.wrap(mapper.writeValueAsBytes(JsonRes.builder().data(data)));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBufferFactory factory = new DefaultDataBufferFactory();
        assert buffer != null;
        DataBuffer wrap = factory.wrap(buffer);
        return response.writeWith(Mono.just(wrap));
    }
}
